package com.hqhy.like.front.cart.service.impl;

import com.hqhy.like.common.enumerator.ServiceCode;
import com.hqhy.like.common.ex.ServiceException;
import com.hqhy.like.common.pojo.authentication.CurrentPrincipal;
import com.hqhy.like.front.cart.converter.DishesToCartConverter;
import com.hqhy.like.front.cart.dao.cache.ICartCacheRepository;
import com.hqhy.like.front.cart.dao.persist.repository.IDishesRepository;


import com.hqhy.like.front.cart.pojo.po.CartPO;
import com.hqhy.like.front.cart.pojo.vo.CartListItemVO;
import com.hqhy.like.front.cart.pojo.vo.DishesStandardVO;
import com.hqhy.like.front.cart.service.ICartService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
/**
 * 处理购物车的业务实现类
 *
 * @author java@tedu.cn
 * @version 3.0
 */

@Slf4j
@Service
public class CartServiceImpl implements ICartService {
    @Autowired
    private ICartCacheRepository cartCacheRepository;
    @Autowired
    private IDishesRepository dishesRepository;

    @Value("${like.service.delete-all-cart-dishId}")
    private Integer defaultClearCarts;

    @Override
    public void add(CurrentPrincipal currentPrincipal, Integer dishId, Integer dishNum) {
        log.debug("开始处理【添加商品到购物车】的业务，当事人：{}，商品：{}，数量：{}", currentPrincipal, dishId, dishNum);
        DishesStandardVO dishes = dishesRepository.getStandardById(dishId);
        if (dishes==null){
            String message = "添加购物车失败，商品数据不存在!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND,message);
        }
        /*if (goods.getIsPutOn()!=1){
            String message = "添加购物车失败，商品已下架！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_INSERT,message);
        }*/
        CartPO cartPO = new CartPO(dishId, dishNum);
        CartPO cartCache = cartCacheRepository.getByUserAndDishes(currentPrincipal.getId(), dishId);
        if (cartCache!=null){
            cartPO.setDishNum(cartCache.getDishNum() + dishNum);
        }
        cartCacheRepository.put(currentPrincipal.getId(), cartPO);
    }

    @Override
    public void delete(CurrentPrincipal currentPrincipal,Integer dishId) {
        log.debug("开始处理【删除购物车中的商品】的业务，当事人：{}，商品：{}", currentPrincipal,dishId);
        if (dishId.equals(defaultClearCarts)){
            List<CartPO> cartPOS = cartCacheRepository.listByUser(currentPrincipal.getId());
            for (CartPO cartPO : cartPOS) {
                cartCacheRepository.deleteByUserAndDishes(currentPrincipal.getId(),cartPO.getDishId());
            }
            return;
        }
        cartCacheRepository.deleteByUserAndDishes(currentPrincipal.getId(),dishId);
    }

    @Override
    public void update(CurrentPrincipal currentPrincipal, Integer dishId, Integer dishNum) {
        log.debug("开始处理【更新购物车中的商品】的业务，当事人：{}，商品：{}，数量：{}", currentPrincipal, dishId, dishNum);
        DishesStandardVO dishes = dishesRepository.getStandardById(dishId);
        if (dishes==null){
            String message = "添加购物车失败，商品数据不存在!";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND,message);
        }
        CartPO cartPO = new CartPO(dishId, dishNum);
        CartPO cartCache = cartCacheRepository.getByUserAndDishes(currentPrincipal.getId(), dishId);
        if (cartCache==null){
            String message = "购物车数据异常，请刷新购物车！";
            throw new ServiceException(ServiceCode.ERROR_CONFLICT, message);
        }
        cartCacheRepository.put(currentPrincipal.getId(), cartPO);
    }

    @Override
    public Integer increaseNum(CurrentPrincipal currentPrincipal, Integer dishId) {
        log.debug("开始处理【将购物车中商品的数量增加1】的业务，当事人：{}，商品：{}", currentPrincipal, dishId);
        return increaseNum(currentPrincipal.getId(),dishId,1);
    }


    @Override
    public Integer reduceNum(CurrentPrincipal currentPrincipal, Integer dishId) {
        log.debug("开始处理【将购物车中商品的数量减少1】的业务，当事人：{}，商品：{}", currentPrincipal, dishId);
        return reduceNum(currentPrincipal.getId(), dishId, 1);
    }


    @Override
    public List<CartListItemVO> list(CurrentPrincipal currentPrincipal) {
        log.debug("开始处理【查询购物车列表】的业务，当事人：{}", currentPrincipal);
        List<CartListItemVO> cartList = new ArrayList<>();
        List<CartPO> cartPOList = cartCacheRepository.listByUser(currentPrincipal.getId());
        for (CartPO cartPO : cartPOList) {
            DishesStandardVO dishes = dishesRepository.getStandardById(cartPO.getDishId());
            if (dishes != null) {
                CartListItemVO cartListItemVO = DishesToCartConverter.convertToCart(cartPO, dishes);
                cartList.add(cartListItemVO);
            }
        }
        return cartList;
    }

    private Integer increaseNum(Long customerId,Integer dishId,Integer num){
        CartPO cartCache = cartCacheRepository.getByUserAndDishes(customerId, dishId);
        Integer newNum = cartCache.getDishNum()+num;
        CartPO cartPO = new CartPO(dishId, newNum);
        cartCacheRepository.put(customerId,cartPO);
        return newNum;
    }

    //将用户购物车中某个商品的数量减少指定的数量。
    private Integer reduceNum(Long customerId,Integer dishId,Integer num){
        CartPO cartCache = cartCacheRepository.getByUserAndDishes(customerId, dishId);
        //如果获取不到购物车信息，即cartCache为null，则直接返回0
        if (cartCache==null){
            return 0;
        }
        //计算新的商品数量newNum，即购物车中该商品原有数量减去要减少的数量num
        Integer newNum = cartCache.getDishNum() - num;
        //如果新的商品数量小于等于0，说明要减少的数量大于或等于原有数量，此时需要从购物车中删除该商品。
        if (newNum<= 0){
            cartCacheRepository.deleteByUserAndDishes(customerId,dishId);
            return 0;
        }

        //如果新的商品数量大于0，说明要减少的数量小于原有数量，此时需要更新购物车中该商品的数量。
        CartPO cartPO = new CartPO(dishId, newNum);
        cartCacheRepository.put(customerId,cartPO);
        return newNum;
    }
}
